package us.mooresr.webtroopmanager.client.activity;

import us.mooresr.webtroopmanager.client.ClientFactory;
import us.mooresr.webtroopmanager.client.TroopManagerService;
import us.mooresr.webtroopmanager.client.TroopManagerServiceAsync;
import us.mooresr.webtroopmanager.client.events.PersonAddedEvent;
import us.mooresr.webtroopmanager.client.place.EditPersonPlace;
import us.mooresr.webtroopmanager.client.ui.EditPersonView;
import us.mooresr.webtroopmanager.shared.Person;
import us.mooresr.webtroopmanager.shared.PersonSummary;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class EditPersonActivity extends MyActivity implements EditPersonView.Presenter {

	
	public EditPersonActivity(EditPersonPlace place, ClientFactory clientFactory) {
		super(place, clientFactory);
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		super.start(panel, eventBus);
		
		EditPersonView editPersonView = clientFactory.getEditPersonView();
		editPersonView.setPresenter(this);
		getPerson(((EditPersonPlace)place).getPersonId());
		panel.setWidget(editPersonView.asWidget());

	}



	@Override
	public void addPerson(Person p) {
		TroopManagerServiceAsync troopManagerService = (TroopManagerServiceAsync) GWT.create(TroopManagerService.class);
		
		
		AsyncCallback<PersonSummary> callback = new AsyncCallback<PersonSummary>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(PersonSummary result) {
				
				clientFactory.getEventBus().fireEvent(new PersonAddedEvent(result));

			}
		};
		
		troopManagerService.addPerson(p, callback);
		
	}
	
	private void getPerson(Long personId) {
		TroopManagerServiceAsync troopManagerService = (TroopManagerServiceAsync) GWT.create(TroopManagerService.class);
		
		if (personId == null) {
			clientFactory.getEditPersonView().setData(null);
			return;
		}
		
		AsyncCallback<Person> callback = new AsyncCallback<Person>() {
			@Override
			public void onFailure(Throwable caught) {
				clientFactory.getEditPersonView().setData(null);
				
			}
			
			@Override
			public void onSuccess(Person result) {
				clientFactory.getEditPersonView().setData(result);
				
			}
		};
		
		troopManagerService.getPerson(personId, callback);
	}

}
